#commands.py
#Timothy Sassone
#Provides easy access to commonly used
#regular expressions and tag commands.

import re
from tag import *

str_legal_exp = r"((\+|\-)?(\d+|\w+\.\w+))+"
re_legal_exp = re.compile(str_legal_exp)

str_exp_comp = r"(\+|\-)?(\d+|\w+\.\w+)"
re_exp_comp = re.compile(str_exp_comp)

str_legal_roll = r"roll " + str_legal_exp
re_legal_roll = re.compile(str_legal_roll)

str_legal_success = r"success" + (" " + str_legal_exp)*2
re_legal_success = re.compile(str_legal_success)

str_legal_opposed = r"opposed" + (" " + str_legal_exp)*3
re_legal_opposed = re.compile(str_legal_opposed)

str_legal_quickex = r"quickex" + (" " + str_legal_exp)*3 + r" \w+"
re_legal_quickex = re.compile(str_legal_quickex)

str_legal_fullex = r"fullex" + (" " + str_legal_exp)*3 + r" \w+" + (" " + str_legal_exp)*2
re_legal_fullex = re.compile(str_legal_fullex)

str_legal_load = r"load \w+"
re_legal_load = re.compile(str_legal_load)

str_legal_view = r"view \w+"
re_legal_view = re.compile(str_legal_view)

def is_legal_expression(string):
    if(re_legal_exp.match(string)==None):
        return False
    else:
        return True

def get_expression_components(string):
    return re_exp_comp.findall(string)

def eval_expression(estring, root_tag):
    expressions = get_expression_components(estring)
    total = 0
    string = ""
    for exp in expressions:
        a = get_expression_value(exp[1], root_tag)
        if(exp[0]=="-"):
            string+=" - "+str(a)
            total -= a
        else:
            if(string==""): string+=str(a)
            else: string+=" + "+str(a)
            total += a
    #print(string + " = " + str(total))
    return total

def get_expression_value(string, root_tag):
    if(string.isdigit()):
        return(int(string))
    else:
        name = string.split(".")[0]
        att = string.split(".")[1]
        tags = root_tag.find_tags("character:"+name+"/stat:"+att+"/rating")
        if(tags!=[]): return int(tags[0].data[0])
        tags = root_tag.find_tags("character:"+name+"/skill:"+att+"/rating")
        if(tags!=[]): return int(tags[0].data[0])
        tags = root_tag.find_tags("character:"+name+"/knowledge_skill:"+att+"/rating")
        if(tags!=[]): return int(tags[0].data[0])
        tags = root_tag.find_tags("character:"+name+"/language_skill:"+att+"/rating")
        if(tags!=[]): return int(tags[0].data[0])
    return 0
